<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="onSearch"
        />
        <!-- 树形组件
        :data="list" 展示数据
        :props="{label:'name',children:'xxx'}" 指定指定节点标签为节点对象的某个属性值
        highlight-current：是否高亮当前选中节点
        expand-on-click-node 是否在点击节点的时候展开或者收缩节点， 默认值为 true，如果为 false，则只有点箭头图标的时候才会展开或者收缩节点。
        default-expand-all 是否默认展开所有节点
        通过ref获取setCurrentKey()设置默认高亮的节点 需要设置 node-key节点的唯一标识  -->
        <el-tree
          ref="myTree"
          node-key="id"
          highlight-current
          :props="{ label: 'name' }"
          :data="list"
          :expand-on-click-node="false"
          default-expand-all
          @current-change="empChange"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="onExport">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table
          v-loading="loading"
          :data="empList"
          style="width: 100%"
        >
          <el-table-column type="selection" width="48" />
          <el-table-column align="center" prop="date" label="头像" width="170">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" size="medium" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt() }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" width="170" />
          <el-table-column prop="mobile" label="手机号" sortable width="170" />
          <el-table-column prop="workNumber" label="工号" sortable width="180" />
          <el-table-column prop="formOfEmployment" label="聘用形式" width="160">
            <template #default="{row}">
              {{ row.formOfEmployment === 1 ? '正式' : '非正式' }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" width="170" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable width="170" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="text" @click="$router.push('/employee/detail/' + row.id)">查看</el-button>
              <el-button type="text" @click="onShowRole(row.id)">角色</el-button>
              <el-popconfirm
                title="确定删除吗？"
                @onConfirm="delEmployee(row.id)"
              >
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end">
          <el-pagination
            :current-page="page"
            :total="total"
            :page-size="pagesize"
            layout="total, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </div>
    </div>
    <import-excel :show-excel-dialog.sync="showExcelDialog" @onSuccess="getEmployees" />
    <el-dialog :visible.sync="visible" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in enabledList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-row type="flex" justify="center">
          <el-button size="mini" type="primary" @click="onUpdateRoles">确定</el-button>
          <el-button size="mini" @click="visible = false">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
let timeID = null
let userId = null
import { saveAs } from 'file-saver'
import { getDepartmentAPI } from '@/api/department'
import convertToTree from '@/utils/data-conversion'
import { assignPolesAPI, delEmployeeAPI, exportAPI, getEmployeeAPI, getEmployeeDetailAPI, getEnabledListAPI } from '@/api/employee'
import importExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: { importExcel },
  data() {
    return {
      keyword: '', // 名字
      list: [],
      empID: null,
      empList: [],
      page: 1, // 当前页
      pagesize: 10, // 每页条数
      total: 1, // 数量总数
      loading: true, // 加载状态
      showExcelDialog: false, // 弹出层状态
      visible: false, // 分配角色弹出层
      enabledList: [], // 已启用角色列表
      roleIds: [] // 员工角色id数组
    }
  },
  async created() {
    // 调用获取员工列表接口
    const result = await getDepartmentAPI()
    // 数据回来后 获取当前节点员工列表
    // 提前存入id 调用方法
    this.empID = result.data[0].id
    this.getEmployees()
    // 调用util的方法转换数据
    this.list = convertToTree(result.data)
    this.$nextTick(() => {
      // 设置默认第一个节点高亮
      this.$refs.myTree.setCurrentKey(result.data[0].id)
    })
  },
  methods: {
    // 获取员工列表方法
    async getEmployees(keyword) {
      this.loading = true
      // 调用api
      const result = await getEmployeeAPI({ page: this.page, pagesize: this.pagesize, departmentId: this.empID, keyword })
      this.loading = false //  关闭loading
      this.empList = result.data.rows
      this.total = result.data.total
    },
    // 监听树组件的current-change 事件 通过形参 获取到当前项的id 改变id 重新发起请求
    empChange(row) {
      this.empID = row.id
      this.page = 1 // 修复bug 发请求前需要把当前页重置为第一页
      this.keyword = '' // 点击子节点需要重新input
      this.getEmployees()
    },
    // 输入框搜索 需要做防抖
    onSearch() {
      clearTimeout(timeID)
      timeID = setTimeout(() => {
        this.getEmployees(this.keyword)
      }, 1000)
    },
    // 点击按钮下载文件
    async onExport() {
      const result = await exportAPI() // 调用api 导出文件
      // 导入file-saver 使用 saveAs下载文件
      saveAs(result, '94员工列表.xlsx')
    },
    // 删除员工事件
    async  delEmployee(id) {
      for (let i = id; i < 100000; i++) {
        await delEmployeeAPI(i) // 调用删除api
        // await delEmployeeAPI(id) // 调用删除api
      // this.$message.success('删除成功')
      // if (this.empList.length === 1) this.page--
      // this.getEmployees()
      }
    },
    // 分配角色
    async onShowRole(id) {
      console.log('id  --->', id)
      const { data } = await getEnabledListAPI() // 调用分配员工角色列表
      const result = await getEmployeeDetailAPI(id) // 复用获取员工详细api
      this.roleIds = result.data.roleIds // 回显数据
      this.enabledList = data
      this.visible = true
      userId = id
    },
    // 点击按钮 修改角色权限
    async onUpdateRoles() {
      await assignPolesAPI({ id: userId, roleIds: this.roleIds }) // 调用更新接口
      this.$message.success('更新用户角色成功') // 提示用户
      this.visible = false // 关闭弹出层
    },
    // 分页器事件
    handleSizeChange(pagesize) {
      this.pagesize = pagesize
      this.getEmployees()
    },
    handleCurrentChange(page) {
      this.page = page
      // 当前页只有一条数据时 需要查询上一页的数据
      if (this.empList.length === 1) this.page--
      this.getEmployees()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 36px;
      width: 36px;
      line-height: 36px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
